﻿using Agile.Infra.Core.Configuration;
using Agile.Shared.WebApi.Authentication.JwtBearer;
using Microsoft.Extensions.Options;
using System.IdentityModel.Tokens.Jwt;

namespace Agile.Service.Admin.WebApi.Controllers
{
    /// <summary>
    /// 系统账号认证服务接口
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AccountController : AgileControllerBase
    {
        /// <summary> 用户登录 </summary> 
        [HttpPost]
        [AllowAnonymous]
        public async Task<ResponseResult<LoginResponse>> Login(LoginRequest request)
        {
            var loginUser = await this.GetService<ISysUserService>().LoginAsync(request);

            var _jwtOptions = this.GetService<IOptions<JWTOptions>>();
            var validationVersion = JwtTokenHelper.GenerateJti();
            var accessToken = JwtTokenHelper.CreateAccessToken(_jwtOptions.Value, validationVersion, loginUser.UserName, loginUser.UserID.ToString(), loginUser.RealName, JwtBearerDefaults.Manager);
            var refreshToken = JwtTokenHelper.CreateRefreshToken(_jwtOptions.Value, validationVersion, loginUser.UserID.ToString());
            var tokenInfo = new LoginResponse
            {
                Token = accessToken.Token,
                Expire = accessToken.Expire,
                RefreshToken = refreshToken.Token,
                RefreshExpire = refreshToken.Expire
            };
            return Result(tokenInfo);
        }

        /// <summary> 刷新Token </summary> 
        [HttpPost]
        [AllowAnonymous]
        public async Task<ResponseResult<LoginResponse>> RefreshToken(RefreshTokenRequest request)
        {
            var _jwtOptions = this.GetService<IOptions<JWTOptions>>();
            var claimOfId = JwtTokenHelper.GetClaimFromRefeshToken(_jwtOptions.Value, request.RefreshToken, JwtRegisteredClaimNames.NameId);
            if (claimOfId is not null)
            {
                var userID = claimOfId.Value.ToLong();
                if (userID is null)
                    return Fail<LoginResponse>("Token过期或无效");

                var validatedInfo = await this.GetService<ISysUserService>().GetUserValidatedInfoAsync(userID.Value);
                if (validatedInfo is null)
                    return Fail<LoginResponse>("Token过期或无效");

                //var jti = JwtTokenHelper.GetClaimFromRefeshToken(_jwtOptions.Value, request.RefreshToken, JwtRegisteredClaimNames.Jti);
                //if (jti is null || jti.Value != validatedInfo.ValidationVersion)
                //    return Fail<LoginResponse>("Token过期或无效");

                var accessToken = JwtTokenHelper.CreateAccessToken(_jwtOptions.Value, validatedInfo.ValidationVersion, validatedInfo.UserName, validatedInfo.UserID.ToString(), validatedInfo.RealName, JwtBearerDefaults.Manager);
                var refreshToken = JwtTokenHelper.CreateRefreshToken(_jwtOptions.Value, validatedInfo.ValidationVersion, validatedInfo.UserID.ToString());

                var tokenInfo = new LoginResponse
                {
                    Token = accessToken.Token,
                    Expire = accessToken.Expire,
                    RefreshToken = refreshToken.Token,
                    RefreshExpire = refreshToken.Expire
                };
                return Result(tokenInfo);
            }
            return Fail<LoginResponse>("Token过期或无效");
        }

        /// <summary> 注销 </summary> 
        [HttpGet]
        public async Task<ResponseResult<bool>> Logout()
        {
            await Task.CompletedTask;
            return Result(true);
        }
    }
}
